# services/device_service.py
from fastapi import WebSocket, WebSocketDisconnect
from typing import List, Dict
from fastapi.responses import JSONResponse

# 存储活动连接和设备状态
active_connections: List[WebSocket] = []
devices: Dict[str, Dict] = {}

async def add_connection(websocket: WebSocket, device_id: str):
    active_connections.append(websocket)
    devices[device_id] = {"websocket": websocket, "status": "online"}
    await notify_device_status(device_id, "online")

async def remove_connection(websocket: WebSocket, device_id: str):
    active_connections.remove(websocket)
    del devices[device_id]
    await notify_device_status(device_id, "offline")

async def notify_device_status(device_id: str, status: str):
    message = f"Device {device_id} is {status}"
    await send_to_all(message)

async def send_to_all(message: str):
    for connection in active_connections:
        await connection.send_text(message)

async def handle_message(device_id: str, websocket: WebSocket):
    try:
        while True:
            data = await websocket.receive_text()
            print(f"Message from {device_id}: {data}")
            await websocket.send_text(f"Message received: {data}")
            await send_to_all(f"Device {device_id} says: {data}")
    except WebSocketDisconnect:
        print(f"Device {device_id} disconnected")
        await remove_connection(websocket, device_id)
